<?php
class Project_Model extends CI_Model{
    function _construct(){
		parent::_construct();
	}
	
	function getProjects($sidx, $sord, $start , $limit) {
		$this->db->order_by($sidx, $sord);
		$this->db->limit($limit, $start);
		$this->db->select('id, name, description, start_date');
		$query = $this->db->get('projects');
		return $query->result_array(); 
	}
	
	function getProjectsCount() {
		return $this->db->count_all_results('projects');
	}
	function create($name,$desc,$users){
	   $data = array(
       	  'name' => $name ,
       	  'description' => $desc 
       );
       $this->db->set('start_date', 'NOW()', FALSE);  
	   $this->db->insert('projects', $data);
	  
	   $id = $this->db->insert_id();
	   if($users!=null){
	   		for($i=0; $i<sizeof($users); $i++){
	   	  		$data = array(
       	 		 	'user_id' => $users[$i] ,
       	    	 	'project_id' => $id
          		);
            	$this->db->insert('users_projects', $data);
	   		}
	   }
    }
    
    function delete ($proj){
    	$this->db->delete('projects', array('id' => $proj)); 
    }
    function get_project($proj){
    	$query=$this->db->get_where('projects', array('id' => $proj));
     	return $query->result_array();
    }
    function update($id,$name,$desc,$users){
    	$data = array(
               'name' => $name,
               'description' => $desc
         );
		$this->db->where('id', $id);
		$this->db->update('projects', $data);
    	
		$this->db->delete('users_projects', array('project_id' => $id));
		
    	if($users!=null){
	   		for($i=0; $i<sizeof($users); $i++){
	   	  		$data = array(
       	 		 	'user_id' => $users[$i] ,
       	    	 	'project_id' => $id
          		);
            	$this->db->insert('users_projects', $data);
	   		}
	   }
    } 
    
    public function get_user_projects($user_id){
    	$this->db->select('projects.id, projects.name');
		$this->db->from('users_projects');
		$this->db->join('projects', 'projects.id = users_projects.project_id', 'left');
		$this->db->where('users_projects.user_id', $user_id);
				
		$query = $this->db->get();
		return $query->result_array();
    }
    public function get_project_users($project_id){
    	$this->db->select('user_id');
		$this->db->from('users_projects');
		$this->db->where('users_projects.project_id', $project_id);
		
		$query = $this->db->get();
		return $query->result_array();
    }
}
?>
